/**
 * Created by 邵亚楠 on 2018/9/8.
 */
var sessionId = sessionStorage.getItem('sessionId');
//var sessionId = 'oQ_An0pr2htuLDV42lwE1LeRM220'
$(function(){
    var id = getQueryString("id")
    var bookId = getQueryString("bookId")
    console.log(bookId)
    var type = getQueryString("type")
    $('#btn').click(function(){
        //var textData = $('.text').val()
        var textData = utf16toEntities($('.text').val())
        //文章评论
        $.ajax({
            url:'https://www.bjdeshangyuan.com/book/api/content/commentSave',
            type:'POST',
            data:{'sessionid':sessionId,'contentId':id,'commentText':textData},
            success:function(r){
                if(r.code == 'USR000'){
                    //console.log(r.data)
                    if(type == 'article'){
                        window.location.href = 'article.html?id='+id+''
                    }

                }
            }
        })
        //书籍评论
        $.ajax({
            url:'https://www.bjdeshangyuan.com/book/api/comment/apiAddComment',
            type:"POST",
            data:{'sessionid':sessionId,'bookId':bookId,'bookcontent':textData},
            success:function(r){
                console.log(r)
                //if(type == 'bookDetail'){
                //    window.location.href = 'bookDetail.html?bookId='+bookId+''
                //}
                window.location.href = 'bookDetail.html?bookId='+bookId+''
            }
        })
    })

    $('.back').click(function(){
        window.history.back()
    })

})

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}


//表情解码
function entitiestoUtf16(str) {
    // 检测出形如&#12345;形式的字符串
    var strObj = utf16toEntities(str);
    var patt = /&#\d+;/g;
    var H, L, code;
    var arr = strObj.match(patt) || [];
    for (var i = 0; i < arr.length; i++) {
        code = arr[i];
        code = code.replace('&#', '').replace(';', '');
        // 高位
        H = Math.floor((code - 0x10000) / 0x400) + 0xD800;
        // 低位
        L = (code - 0x10000) % 0x400 + 0xDC00;
        code = "&#" + code + ";";
        var s = String.fromCharCode(H, L);
        strObj.replace(code, s);
    }
    return strObj;
}

/**
 * input 输入框处理输入法表情符号
 * @param str 输入框的 value 值
 */
function utf16toEntities(str) {
    var patt = /[\ud800-\udbff][\udc00-\udfff]/g;
    // 检测utf16字符正则
    str = str.replace(patt, function (char) {
        var H, L, code;
        if (char.length === 2) {
            H = char.charCodeAt(0);
            // 取出高位
            L = char.charCodeAt(1);
            // 取出低位
            code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00;
            // 转换算法
            return "&#" + code + ";";
        } else {
            return char;
        }
    });
    return str;
}